package com.sykj.why.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author Cheng.Peng
 * @version 2.0
 * @update wy
 * @time 2018年10月29日15:23:00
 * @Description TODO
 */
public class CookieUtil {


    /**
     * 设置cookie
     *
     * @param response 响应头
     * @param key
     * @param value
     * @param maxAge
     */
    public static void setCookie(HttpServletResponse response, String key, String value, int maxAge) {
        Cookie cookie = null;
        try {
            if (StringUtils.isNotBlank(value)) {
                value = URLEncoder.encode(value, "utf-8");
            }
            cookie = new Cookie(key, value);
            cookie.setPath("/");
            cookie.setMaxAge(maxAge);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.addCookie(cookie);
    }


    public static String getValue(HttpServletRequest request, String cName, String value) throws UnsupportedEncodingException {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cName.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return URLDecoder.decode(value, "utf-8");
    }


    public static Cookie getCookie(HttpServletRequest request, String cName) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cName.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

}
